/**
 * 
 */
package com.scaffold.springmvc.action;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import wangjg.commons.dao.ResultMapping.ColumnInfo;

import com.scaffold.BasicBizAction;
import com.scaffold.springmvc.dao.SqlDAO.ResultVo;
import com.scaffold.springmvc.service.DbService;

/**
 * @author wangjg
 */
@Controller
public class SQLAction extends BasicBizAction {
	@Autowired
	private DbService dbService;
	
	@RequestMapping("/sql/exec.xhtml")
	public String exec(ModelMap model, String sql) throws SQLException{
		if(sql!=null && sql.length()>0){
			long startTime = System.currentTimeMillis();
			ResultVo result = dbService.exec(sql.trim());
			long useTime = System.currentTimeMillis() - startTime;
			model.put("time", useTime);
			viewData(model, result);
		}
		return "db/index.vm";
	}
	
	@RequestMapping("/sql/query.xhtml")
	public String query(ModelMap model, String sql) throws SQLException{
		if(sql!=null && sql.length()>0 && dbService.isQuerySql(sql)){
			long startTime = System.currentTimeMillis();
			ResultVo result = dbService.query(sql.trim());
			long useTime = System.currentTimeMillis()-startTime;
			model.put("time", useTime);
			viewData(model, result);
		}
		return "db/index.vm";
	}
	
	@RequestMapping("/sql/tableMetaData.xhtml")
	public String metaData(ModelMap model, String table) throws SQLException{
		if(table!=null && table.length()>0){
			List<ColumnInfo> result = dbService.queryColumnInfo(table);
			model.put("list", result);
		}
		ResultVo tables = dbService.getDatabaseMetaData("TABLE");
		model.put("tables", tables);
		return "db/tableMetaData.vm";
	}

	@RequestMapping("/sql/dbMetaData.xhtml")
	public String dbMetaData(ModelMap model, String types) throws SQLException{
		if(true){
			long startTime = System.currentTimeMillis();
			String[] typeArray = null;
			if(types!=null && types.length()>0){
				typeArray = types.split(",");
			}
			ResultVo result = this.dbService.getDatabaseMetaData(typeArray);
			long useTime = System.currentTimeMillis()-startTime;
			model.put("time", useTime);
			viewData(model, result);
		}
		return "db/dbMetaData.vm";
	}
	
	private void viewData(ModelMap model, ResultVo result){
		model.put("updateRowNums", result.getRowsNum());
		if(result.getColNames()!=null){
			model.put("colNames", result.getColNames());
			model.put("colNums", result.getColNames().size());	
		}
		
		model.put("list", result.getRowsData());
		model.put("rowNums", result.getRowsData()==null?0:result.getRowsData().size());
	}
}
